package com.pgcomb.poweriot.alarmservice.alarm.sendAlarm;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * @author zhengheqi
 * @version 1.0
 * @description: 邮件告警
 * @date 2021/5/31 16:45
 */
@Slf4j
@Component
public class EmailSender {
    @Resource
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String emailUsername;

    public boolean sendMail(String content, List<String> mailTo) {
        if(CollectionUtils.isEmpty(mailTo)){
            return false;
        }

        mailTo.forEach(emailTo ->{
            try {

                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
                helper.setFrom(emailUsername, "电力监管平台");
                helper.setTo(emailTo);
                helper.setSubject("设备监控中心告警");
                helper.setText(content, true);

                javaMailSender.send(mimeMessage);
                log.info("send message to :{} access", emailTo);
            } catch (Exception e) {
                log.error(">>>>>>>>>> alarm email send error", e);
            }
        });

        return true;
    }

    /**
     * load email alarm template
     */
    public static final String loadEmailJobAlarmTemplate(){
        String mailBodyTemplate = "<h5>监控告警明细：</span>" +
                "<table border=\"1\" cellpadding=\"3\" style=\"border-collapse:collapse; width:80%;\" >\n" +
                "   <thead style=\"font-weight: bold;color: #ffffff;background-color: #ff8c00;\" >" +
                "      <tr>\n" +
//                "         <td width=\"20%\" >工程</td>\n" +
                "         <td width=\"10%\" >园区ID</td>\n" +
                "         <td width=\"20%\" >配电单元</td>\n" +
                "         <td width=\"20%\" >设备名</td>\n" +
                "         <td width=\"50%\" >告警信息</td>\n" +
                "      </tr>\n" +
                "   </thead>\n" +
                "   <tbody>\n" +
                "      <tr>\n" +
                "         <td>{0}</td>\n" +
                "         <td>{1}</td>\n" +
                "         <td>{2}</td>\n" +
                "         <td>{3}</td>\n" +
//                "         <td>{4}</td>\n" +
                "      </tr>\n" +
                "   </tbody>\n" +
                "</table>";

        return mailBodyTemplate;
    }
}
